/**
 * @created by zhangpeng18 on 2019-8-5 10:40:22
 * @updated by
 * @description Java类驱动管理
 */
define(['./custom/widgets/js/yufpSelectParam.js'], function (require, exports) {
    /**
     * 页面加载完成时触发
     * @param hashCode 路由ID
     * @param data 传递数据对象
     * @param cite 页面站点信息
     */
    exports.ready = function (hashCode, data, cite) {
        yufp.lookup.reg('PROXY_FLAG');

        var driverTypes = [];
        var dynamicList =[];

        yufp.service.request({
            method: 'GET',
            url:  "api/use/plats/driver/queryDriverTypes",
            data: {},
            async:false,
            callback: function (code, message, response) {
                if(response.code!=0){
                   // _this.$message({message:"",type:"warning"});
                }else{

                     driverTypes.splice(0);
                    for(let i=0;i<response.data.length;i++){
                        driverTypes.push( { key: response.data[i].driverType,value:response.data[i].driverName });

                        var dynamicObj = {
                            order: 0,
                            column: 2,
                            title: '详细配置',
                            collapse: true,
                            fields: response.data[i].datas
                        };

                        var object ={key:response.data[i].key,dynamicObj:[dynamicObj]};
                        dynamicList.push(object);
                    }



                }

            }
        });

        yufp.custom.vue({
            el: cite.el,
            data: function () {

                var _this = this;
                /**
                 * 校验自定义参数代码字段，必须以 $ 开头
                 */
                var paramCodeValidate = function (rule, value, callback) {
                    var reg = /^\$/;
                    if (value && reg.test(value)) {
                        callback();
                    } else if (value && !reg.test(value)) {
                        callback(new Error('自定义参数代码字段，请以 $ 开头'));
                    } else if (value === '') {
                        callback(new Error('自定义参数代码字段，请以 $ 开头'));
                    } else {
                        callback();
                    }
                };
                return {
                    addFnButton: !yufp.session.checkCtrl('addFn'),
                    updateFnButton: !yufp.session.checkCtrl('updateFn'),
                    deleteFnButton: !yufp.session.checkCtrl('deleteFn'),
                    treeDataUrl:"api/use/plats/apps/getTreeWftList",
					tbHeight:'0',

                    dataUrl: 'api/use/plats/driver/queryDriverList',

                    param: { UNITID: '0000', LEVELUNIT: '1' },
                    driverTypes:driverTypes,
                    activeTabName: "basicInfo",
                    collActiveNames: "basicInfo",
                    fieldsList:[],
                    saveBtnShow: true,
                    cancelBtnShow: true,
                    addBtnShow: false,
                    saveDisabled: false,
                    formdata: {},
                    extFormData:{},
                    async: false,
                    rule: [
                        { validator: paramCodeValidate, trigger: 'blur' }
                    ],
                    height: yufp.frame.size().height - 95,
                    dialogVisible: false,
                    formDisabled: false,
                    classCodeDisabled: false,
                    viewTitleArrry: ['第三方驱动新增', '第三方驱动修改','第三方驱动查看'],
                    viewTitle: '',
                    propTabaleData: [],
                    appCodeShow: true,
                    propTableData: [],
                    currentDriverType:'',
                    dynamicList:dynamicList,
                    currentFormData: {},
                    defaultFormData:{},
                    isLoadData: false,
                    searchFormdata: {},
                    nodeData: '', // 在新增表格数据时需要先获取当前树节点，再把一条新的记录加到这个节点下的表格里,
                    nodeLeaf: false,
                    queryFields:[
                        {placeholder: '驱动类型', field: 'driverType', type: 'select',options:driverTypes},
                        {placeholder: '驱动缩写', field: 'classCode', type: 'input'},
                        {placeholder: '驱动名称', field: 'className', type: 'input'}
                    ],
                    queryButtons: [
                        {label: '搜索', op: 'submit', type: 'primary',  click: function (model, valid) {
                                _this.reloadData();
                            }},
                        {label: '重置', op: 'reset'}
                    ],
                    isReadOnly: false,
                    agentIds: [
                    ],
                    nodeTemp: {},

                    dynamicObj: [
                        {
                            order: 0,
                            column: 2,
                            title: '驱动详情',
                            collapse: true,
                            fields: [
                            ]
                        }
                    ]
                };
            },

            mounted:function(){
				var _this = this;
				//测试
				_this.$nextTick(function(){
						var tableBox = _this.$refs.tableBox;
						let a = tableBox.getBoundingClientRect().top + 28;
						var theight = `calc(100vh - ${a}px - 64px)`;
						_this.tbHeight = theight;		
				});
            },


            methods: {

                reloadData: function(){
                    var _this = this;

                    _this.searchFormdata.appCode = _this.nodeTemp.appCode;
                    var paramObj = _this.searchFormdata;
                    _this.$refs.refTable.remoteData({condition:paramObj});
                },

                getDynamicAgentOptions: function(  optionKey ) {
                    var _this =this;

                    for (let i = 0; i < _this.dynamicList.length; i++) {
                        if (_this.dynamicList[i].key === _this.currentDriverType) { //动态列表信息
                             for( let j=0;j<_this.dynamicList[i].dynamicObj[0].fields.length;j++){
                                if(_this.dynamicList[i].dynamicObj[0].fields[j].field===optionKey){
                                    return _this.dynamicList[i].dynamicObj[0].fields[j].options;
                                }
                            }

                        }
                    }

                    return null;
                },

                loadDefaultDriver: function(driver){
                    var _this = this;

                    yufp.service.request({
                        method: 'GET',
                        url:  "api/use/plats/driver/queryDefaultValue",
                        data: {driverType:  driver},
                        async:false,
                        callback: function (code, message, response) {
                            if(response.code!=0){
                                _this.$message({message:response.message,type:"warning"});
                            }else{
                                 _this.defaultFormData = response.data.formDataMap;
                            }

                        }
                    });
                },

                //下一步
                nextStep: function(){
                    var _this = this;
                    var validate1 = false;
                    var validate2 = false;
                    _this.$refs.refForm.validate(function (valid) {
                        validate1 = valid;
                    });
                    _this.$refs.refPropTable.validate(function (field) {
                        validate2 = field==null;
                    });
                

                    if(!validate1 || !validate2){
                        return ;
                    }

                    _this.activeTabName = "paramInfoInfo";
                    _this.$nextTick(function () {
                        if(!_this.addFlag&&!_this.isLoadData){
                            _this.isLoadData = true;
                            yufp.clone( _this.currentFormData ,_this.$refs[_this.currentDriverType][0].formdata);
                        }else if(_this.addFlag ){

                            yufp.clone( _this.defaultFormData,_this.$refs[_this.currentDriverType][0].formdata);
                        }



                    })
                },

                lastStepFn: function(){
                    var _this = this;
                    if(_this.addFlag ){
                        yufp.clone(_this.$refs[_this.currentDriverType][0].formdata, _this.defaultFormData);
                    }
                    _this.activeTabName = "basicInfo";

                },

                changeDriverType: function(val){
                    var _this =this;

                    var _url = "";

                    if(val==null||val==''){
                        _this.currentDriverType = "";
                        //_this.dynamicObj.splice(0);
                        return ;
                    }else{
                        _this.currentDriverType = val.substring(1);

                        var appCode ="";
                        if(_this.addFlag){
                            appCode= _this.formdata.appCode;
                        }else{
                            appCode = _this.refTemp.appCode
                        }

                        this.getAgentIds(appCode);
                        if(_this.addFlag){
                            _this.loadDefaultDriver(val);
                        }

                        }
                    },



                /**
                 * 获取参数列表子组件选中的行数据
                 */
                getSelectedData: function (data) {
                    var _this = this;
                    _this.$refs.refPropTable.selections[0].paramValue = '{#' + data[0].paramValue + '#}';
                },
                /**
                 * 取消
                 */
                cancelFn: function () {
                    var _this = this;
                    _this.dynamicObj[0].fields.splice(0);
                    _this.dialogVisible = false;

                },


                /**
                 * 保存
                 */
                saveFn: function () {
                    var _this = this;
                    var validate = false;
                    _this.$refs.refForm.validate(function (valid) {
                        validate = valid;
                    });
                    if (!validate) {
                        _this.activeTabName = "basicInfo";
                        return;
                    }

                    _this.$refs[_this.currentDriverType][0].validate(function (valid) {
                        validate = valid;
                    });

                    if(!validate){
                        _this.activeTabName = "paramInfoInfo";
                        return ;
                    }

                    var paramObj =  _this.formdata;


                    if(paramObj.useParamValues!=null){
                        paramObj.useParamValues.splice(0);
                    }else{
                        paramObj.useParamValues = new Array();
                    }

                    for(let i=0;i<_this.propTableData.length;i++){
                        paramObj.useParamValues.push(_this.propTableData[i]);
                    }

                    paramObj.formDataMap = _this.$refs[_this.currentDriverType][0].formdata;

                    let urlparam = "";
                    if(_this.addFlag){
                        urlparam = 'api/use/plats/driver/addDriver';
                    }else{
                        urlparam = 'api/use/plats/driver/updateDriver';
                    }


                    yufp.service.request({
                        method: 'POST',
                        url:urlparam,
                        data: paramObj,
                        callback: function (code, message, response) {

                            if(response.code==0) {
                                _this.reloadData();

                                _this.$message('操作成功');
                                _this.dialogVisible = false;
                            }else{
                                _this.$message({message:response.message,type:"warning"});
                            }
                        }
                    });

                },
                /**
                 * 控制保存按钮、xdialog、表单的状态
                 * @param viewType 表单类型
                 * @param editable 可编辑,默认false
                 */
                switchStatus: function (viewType, editable) {
                    var _this = this;
                    _this.viewType = viewType;
                    _this.dialogVisible = true;
                    _this.formDisabled = !editable;
                    _this.saveBtnShow = editable;
                    _this.cancelBtnShow = editable;
                },
                /**
                 * 新增参数
                 */
                propAddFn: function () {
                    var _this = this;
                    var obj = {
                        paramCode: '',
                        paramName: '',
                        paramValue: ''
                    };
                    _this.propTableData.push(obj);
                },
                /**
                 * 删除参数
                 */
                propDeleteFN: function () {
                    var _this = this;

                    let selectDatas = _this.$refs.refPropTable.selections;
                    for (let jdx = _this.propTableData.length-1; jdx >= 0; jdx--) {
                        for (let idx = 0; selectDatas.length > idx; idx++) {
                            if (_this.propTableData[jdx] == selectDatas[idx]) {
                                _this.propTableData.splice(jdx, 1);
                                break;
                            }
                        }

                    }
                },
                /**
                 * 点击树的结点，加载对应的数据
                 */
                nodeClickFn: function (nodeData, node, self) {
                    var _this = this;
                    var appCode ="";
                    var appName = "";
                    if(nodeData.appCode!='0000'){
                        _this.nodeLeaf = true;
                        appCode =  nodeData.appCode;
                        appName = nodeData.appName;
                    }else{
                        _this.nodeLeaf = false;
                    }
                    _this.nodeTemp.appCode = appCode;
                    _this.nodeTemp.appName = appName;
                    this.reloadData();
                },
                /**
                 * 新增
                 */
                addFn: function () {
                    var _this = this ;
                    _this.isReadOnly = false;
                    _this.dialogVisible = true;
                    _this.viewTitle = _this.viewTitleArrry[0];
                    _this.addFlag = true;
                    _this.saveDisabled = false;
                    _this.activeTabName = "basicInfo";

                    _this.$nextTick(function () {
                        _this.$refs.refForm.resetFields();
                        _this.propTableData = [];
                        _this.formdata.appCode = _this.nodeTemp.appCode;
                        _this.formdata.appName = _this.nodeTemp.appName;
                    });
                },
                /**
                 * 修改
                 */
                modifyFn: function () {
                    var _this = this;
                    if (_this.$refs.refTable.selections.length != 1) {
                        _this.$message({ message: '请先选择一条记录', type: 'warning' });
                        return;
                    }
                    _this.activeTabName = "basicInfo";
                    _this.isReadOnly = true;
                    _this.isLoadData = false;
                    _this.nodeTemp.appCode = _this.$refs.refTable.selections[0].appCode;
                    _this.getAgentIds(_this.$refs.refTable.selections[0].appCode);
                    _this.viewTitle = _this.viewTitleArrry[1];
                    _this.saveDisabled = false;
                    _this.dialogVisible = true;
                    _this.addFlag = false;
                    _this.refTemp = _this.$refs.refTable.selections[0];

                    //queryCommonParamValue

                    yufp.service.request({
                        method: 'GET',
                        url:  "api/use/plats/driver/queryDriverDetail",
                        data: {driverType:  _this.refTemp.driverType,
                                appCode:  _this.refTemp.appCode,
                                classCode: _this.refTemp.classCode},
                        async:false,
                        callback: function (code, message, response) {
                            if(response.code!=0){
                                _this.$message({message:response.message,type:"warning"});
                            }else{
                                _this.dialogVisible = true;
                                _this.currentDriverType = _this.refTemp.driverType.substring(1);
                                _this.$nextTick(function () {
                                    _this.$refs.refForm.resetFields();
                                    _this.propTableData.splice(0);
                                    yufp.clone(_this.refTemp, _this.formdata);
                                    _this.formdata.agentId = response.data.agentId;
                                    for (var i = 0; i < response.data.useParamValues.length; i++) {
                                        _this.propTableData.push(response.data.useParamValues[i]);
                                    }
                                    _this.currentFormData =  response.data.formDataMap;
                                });

                            }

                        }
                    });

                },

                viewFn: function(obj){
                    var _this = this;

                    _this.activeTabName = "basicInfo";
                    _this.isReadOnly = true;
                    _this.nodeTemp.appCode = obj.appCode;
                    _this.getAgentIds(obj.appCode);
                    _this.viewTitle = _this.viewTitleArrry[2];
                    _this.dialogVisible = true;
                    _this.saveDisabled = true;
                    _this.addFlag = false;
                    _this.refTemp =obj;
                    _this.isLoadData = false;
                   // var data = obj.useParamValues;


                    yufp.service.request({
                        method: 'GET',
                        url:  "api/use/plats/driver/queryDriverDetail",
                        data: {driverType: obj.driverType,
                            appCode:  obj.appCode,
                            classCode: obj.classCode},
                        async:false,
                        callback: function (code, message, response) {
                            if(response.code!=0){
                                //_this.$message({message:response.message,type:"warning"});
                            }else{
                                _this.dialogVisible = true;
                                _this.currentDriverType = _this.refTemp.driverType.substring(1);
                                _this.$nextTick(function () {
                                    _this.$refs.refForm.resetFields();
                                    _this.propTableData.splice(0);
                                    yufp.clone(_this.refTemp, _this.formdata);
                                    _this.formdata.agentId = response.data.agentId;
                                    for (var i = 0; i < response.data.useParamValues.length; i++) {
                                        _this.propTableData.push(response.data.useParamValues[i]);
                                    }
                                    _this.currentFormData =  response.data.formDataMap;
                                });

                            }

                        }
                    });

                },


                /**
                 * 删除
                 */
                deleteFn: function () {
                    var _this = this;
                    var selections = _this.$refs.refTable.selections;
                    if (selections.length < 1) {
                        _this.$message({ message: '请先至少选择一条记录', type: 'warning' });
                        return;
                    }
                    var len = selections.length, arr = [];
                    for (var i = 0; i < len; i++) {
                        arr.push(selections[i].id);
                    }
                    _this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true,
                        callback: function (action) {
                            if (action === 'confirm') {
                                yufp.service.request({
                                    method: 'DELETE',
                                    url:  "api/use/plats/driver/deleteDriver",
                                    data: selections[0],
                                    callback: function (code, message, response) {
                                        if(response.code!=0){
                                            isOk = false;
                                            _this.$message(response.message);
                                        }else{
                                            _this.$message('操作成功');
                                            _this.reloadData();

                                        }

                                    }
                                });
                            }
                        }
                    });
                },

                getAgentIds:function(appCode){

                    var _this = this;
                    _this.agentIds.splice(0);
                    const  model ={};
                    model.appCode = appCode;

                    var params = { condition: JSON.stringify(model) };

                    var initObj ={};
                    initObj.key=" ";
                    initObj.value="虚拟代理";
                    _this.agentIds.push(initObj);
                    yufp.service.request({
                        method: 'GET',
                        url:  "api/use/plats/apps/queryWftAppList",
                        data: params,
                        async:false,
                        callback: function (code, message, response) {

                            if(response.data.length>0){
                                const wftAgtList = response.data[0].wftAgtList;

                                if(wftAgtList!=null)
                                    for(let j=0;j<wftAgtList.length;j++){
                                        var obj={};
                                        obj.key=wftAgtList[j].agentId;
                                        obj.value=wftAgtList[j].agentName;
                                        _this.agentIds.push(obj);

                                    }
                            }
                        }
                    });

                },

                checkClassCode:function( isOk ){

                    var _this = this;
                    var paramObj = _this.formdata;
                    paramObj.useParamValues = [];
                    if(!_this.addFlag){
                        return ;
                    }

                    yufp.service.request({
                        method: 'GET',
                        url:  "api/use/plats/dscfg/checkClassCode",
                        data: paramObj,
                        async:false,
                        callback: function (code, message, response) {
                            if(response.code!=0){
                                isOk = false;
                                _this.$message(response.message);
                            }else{
                                if(!response.data){
                                    isOk = false;
                                    _this.$message('该驱动缩写在系统中已经存在');
                                }
                            }

                        }
                    });
                },
            },

        });
    };
});